<?php

namespace App\Console\Commands;

use App\Models\GoodsSeckill;
use App\Models\GoodsSeckillConfig;
use App\Models\StoreGoods;
use App\Service\EsasticSearch;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class DataPreheat extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'DataPreheat';//数据预热（秒杀）

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     *///冯保杰 11.11 19:03数据预热
    public function handle()
    {
        $goodsData = GoodsSeckillConfig::get();//获取所有的数据
        if (empty($goodsData)) die();
        $goodsData = $goodsData->toArray();
        foreach ($goodsData as $key => $value) {
            $time = time();
            if (strtotime($value['action_time']) - $time <= 86400 && strtotime($value['action_time']) - $time > 0)//如果开始时间在今天时，则进行全部数据预热
            {
                Log::info('商品id为'.$value['id'].'的商品准备数据预热');
                $db = GoodsSeckill::where('config_id',$value['id'])->first();//循环获取单条数据
                if (empty($db))break;
                $db = $db->toArray();
                for ($i = 1; $i <= $db['seckill_goods_store']; $i++) {
                    Redis::rpush('goods_id-'.$db['goods_id'],'number_'.$i);
                }
                EsasticSearch::createDatabase('seckill','activity_title');//索引名称，要搜索的字段
                EsasticSearch::createData('seckill',$db);
            }
            if (strtotime($value['action_time']) > $time)//如果当前的时间戳大于数据库中的时间，说明秒杀已经开始，修改状态值  抢购开始
            {
                $db = GoodsSeckillConfig::where('id', $value['id'])->first()->toArray();//循环获取单条数据
                $db['state'] = 1;//修改状态 0未开始 1已开始 2已结束 3异常
                $db = GoodsSeckillConfig::where('id', $value['id'])->update($db);//修改状态
                if ($db) {
                    Log::info($key . '已开始秒杀');
                }
            }
            if (strtotime($value['finish_time']) < $time)//如果当前的时间戳小于数据库中的结束时间，说明秒杀已经开始，修改状态值  抢购结束
            {
                $db = GoodsSeckillConfig::where('id', $value['id'])->first()->toArray();//循环获取单条数据
                $db['state'] = 2;//修改状态 0未开始 1已开始 2已结束 3异常
                $db = GoodsSeckillConfig::where('id', $value['id'])->update($db);//修改状态
                if ($db) {
                    Log::info($key . '已结束秒杀');
                }
            }
        }
    }
}
